package com.zheng.shop.admin.controller.product;

import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.validator.DecimalValidator;
import com.zheng.common.validator.LengthValidator;
import com.zheng.common.validator.NotNullValidator;
import com.zheng.common.validator.SizeValidator;
import com.zheng.shop.common.constant.ShopResult;
import com.zheng.shop.common.constant.ShopResultConstant;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.model.ShopCategory;
import com.zheng.shop.dao.model.ShopDict;
import com.zheng.shop.rpc.api.ShopCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/11
 * Time: 11:35
 */
@Controller
@Api(value = "商品分类管理", description = "商品分类管理")
@RequestMapping("/manage/product/category")
public class CategoryController extends BaseController {
    private static Logger _log = LoggerFactory.getLogger(CategoryController.class);
    @Autowired
    private ShopCategoryService categoryService;

    @ApiOperation(value = "商品分类首页")
    @RequiresPermissions("product:category:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "/manage/product/productCategory/index.jsp";
    }

    @ApiOperation(value = "获取所有商品分类")
    @RequiresPermissions("product:category:read")
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Object all() {
        List<ShopCategory> categoryList = categoryService.selectList(null);
        return new ShopResult(ShopResultConstant.SUCCESS, categoryList);
    }

    @ApiOperation(value = "商品分类列表")
    @RequiresPermissions("product:category:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, defaultValue = "", value = "searchText") String searchText,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       @RequestParam(required = false, value = "id") Integer id) {
        Wrapper<ShopCategory> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        if (StringUtils.isNotBlank(searchText)) {
            wrapper.like("name", searchText);
        }
        if (null != id) {
            wrapper.where("pid=" + id);
        }
        Page<ShopCategory> page = categoryService.selectPage(new Page<>(pageNumber, pageSize), wrapper);
        int total = categoryService.selectCount(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", page.getRecords());
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增商品分类")
    @RequiresPermissions("product:category:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model, Integer pId) {
        EntityWrapper<ShopCategory> categoryEntityWrapper = new EntityWrapper<>();
        categoryEntityWrapper.orderBy("sort desc");
        List<ShopCategory> categoryList = categoryService.selectList(categoryEntityWrapper);
        model.addAttribute("productCategoryList", categoryList);
        if (null != pId) {
            if (pId == 0) {
                ShopCategory productCategory = new ShopCategory();
                productCategory.setId(0);
                productCategory.setName("顶级");
                model.addAttribute("productCategory", productCategory);
            } else {
                ShopCategory productCategory = categoryService.selectById(pId);
                model.addAttribute("productCategory", productCategory);
            }
        }
        return "/manage/product/productCategory/create.jsp";
    }

    @ApiOperation(value = "新增商品分类")
    @RequiresPermissions("product:category:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody JSONObject param) {
        ShopCategory productCategory = param.toJavaObject(ShopCategory.class);
        ComplexResult result = FluentValidator.checkAll()
                .on(productCategory.getName(), new LengthValidator(0, 100, "分类名称"))
                .on(productCategory.getPid(), new NotNullValidator("父分类"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        boolean copyAttribute = param.getBoolean("copyAttribute");
        boolean copyParam = param.getBoolean("copyParam");
        try {
            categoryService.createProductCategory(productCategory, copyAttribute, copyParam);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
    }

    @ApiOperation(value = "修改商品分类")
    @RequiresPermissions("product:category:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") Integer id, Model model) {
        ShopCategory category = categoryService.selectById(id);
        ShopCategory pCategory = categoryService.selectById(category.getPid());
        if (null == pCategory) {
            pCategory = new ShopCategory();
            pCategory.setId(0);
            pCategory.setName("顶级");
        }
        EntityWrapper<ShopCategory> categoryEntityWrapper = new EntityWrapper<>();
        categoryEntityWrapper.orderBy("sort desc");
        List<ShopCategory> productCategoryList = categoryService.selectList(categoryEntityWrapper);

        model.addAttribute("productCategoryList", productCategoryList);
        model.addAttribute("category", category);
        model.addAttribute("pCategory", pCategory);
        return "/manage/product/productCategory/update.jsp";
    }

    @ApiOperation(value = "修改商品分类")
    @RequiresPermissions("product:category:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody ShopCategory productCategory) {
        boolean flag;
        ComplexResult result = FluentValidator.checkAll()
                .on(productCategory.getName(), new LengthValidator(0, 100, "分类名称"))
                .on(productCategory.getPid(), new NotNullValidator("父分类"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            flag = categoryService.updateProductCategory(productCategory);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        if (flag) {
            return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS);
        }
        return new ShopResult(ShopResultConstant.FAILED, ShopResultConstant.FAILED.getMessage());
    }

    @ApiOperation(value = "删除商品分类")
    @RequiresPermissions("product:category:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestBody List<Integer> ids) {
        boolean delete = false;
        try {
            delete = categoryService.deleteBatchCategory(ids);
        } catch (Exception e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        if (delete) {
            return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getMessage());
        }
        return new ShopResult(ShopResultConstant.FAILED, ShopResultConstant.FAILED.getMessage());
    }
}
